<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base href="<%=basePath%>"/>
    <title>茶叶进销存系统 - 新增物流</title>
    <link rel="stylesheet" href="css/global.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        .form-container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-regular);
        }
        .form-control {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s;
            background-color: #fff;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(139, 158, 107, 0.2);
        }
        .btn-group {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
        }
        .tea-icon {
            color: var(--primary-color);
            margin-right: 5px;
        }
        .form-header {
            font-size: 18px;
            color: var(--text-regular);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }
        .alert {
            padding: 10px 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            background-color: #fef0f0;
            color: var(--danger-color);
            border: 1px solid #fde2e2;
        }
        .form-row {
            display: flex;
            gap: 20px;
        }
        .form-col {
            flex: 1;
        }
    </style>
</head>
<body>
<div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-logo" onclick="toggleSidebar()">
            <span><i class="fas fa-leaf tea-icon"></i> 茶叶进销存系统</span>
        </div>

        <div class="sidebar-menu">
            <div
                    class="menu-item "
                    onclick="location.href='views/home.jsp'"
            >
                <i class="fas fa-home"></i>
                <span>系统首页</span>
            </div>
            <div class="menu-item" onclick="location.href='TeaServlet'">
                <i class="fas fa-coffee"></i>
                <span>茶叶管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CategoryServlet'">
                <i class="fas fa-tags"></i>
                <span>分类管理</span>
            </div>
            <div class="menu-item" onclick="location.href='WarehouseServlet'">
                <i class="fas fa-boxes"></i>
                <span>仓库管理</span>
            </div>
            <div class="menu-item" onclick="location.href='OrderServlet'">
                <i class="fas fa-receipt"></i>
                <span>订单管理</span>
            </div>
            <div class="menu-item active" onclick="location.href='LogisticsServlet'">
                <i class="fas fa-shipping-fast"></i>
                <span>物流管理</span>
            </div>
            <div class="menu-item" onclick="location.href='SupplierServlet'">
                <i class="fas fa-truck"></i>
                <span>供应商管理</span>
            </div>
            <div class="menu-item" onclick="location.href='<%=basePath%>purchase/list'">
                <i class="fas fa-truck"></i>
                <span>采购管理</span>
            </div>
            <div class="menu-item" onclick="location.href='CustomerServlet'">
                <i class="fas fa-users"></i>
                <span>客户管理</span>
            </div>
            <div class="menu-item" onclick="location.href='AddressServlet'">
                <i class="fas fa-map-marker-alt"></i>
                <span>地址管理</span>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航栏 -->
        <div class="navbar">
            <div class="navbar-left">
                <h3><i class="fas fa-plus-circle tea-icon"></i> 新增物流</h3>
            </div>
            <div class="navbar-right">
                <span><i class="fas fa-user tea-icon"></i> 欢迎，${ username}管理员</span>
                <a href="logout" class="el-link el-link--danger ml-10"><i class="fas fa-sign-out-alt"></i> 退出</a>
            </div>
        </div>

        <!-- 内容卡片 -->
        <div class="el-card fade-in">
            <div class="el-card__header">
                <span><i class="fas fa-info-circle tea-icon"></i> 物流信息</span>
            </div>
            <div class="el-card__body">
                <form action="LogisticsServlet?action=${not empty order ? 'ship' : 'add'}" method="post" class="form-container">
                    <!-- 错误信息显示 -->
                    <c:if test="${not empty error}">
                        <div class="alert"><i class="fas fa-exclamation-circle"></i> ${error}</div>
                    </c:if>

                    <div class="form-header">
                        <i class="fas fa-shipping-fast tea-icon"></i> 基本信息
                    </div>

                    <!-- 订单信息显示 -->
                    <c:if test="${not empty order}">
                        <div class="form-group">
                            <label><i class="fas fa-receipt tea-icon"></i> 订单信息</label>
                            <div style="background: #f8f9fa; padding: 15px; border-radius: 4px; border: 1px solid #e1e5e9;">
                                <p><strong>订单号：</strong>${order.order_no}</p>
                                <p><strong>客户：</strong>${order.customer_name}</p>
                                <p><strong>总金额：</strong>¥${order.total_amount}</p>
                                <p><strong>订单商品：</strong></p>
                                <ul style="margin: 10px 0; padding-left: 20px;">
                                    <c:forEach items="${orderItems}" var="item">
                                        <li>${item.tea_name} - 数量: ${item.quantity} ${item.unit} - 单价: ¥${item.unit_price}</li>
                                    </c:forEach>
                                </ul>
                            </div>
                            <input type="hidden" name="order_id" value="${order.order_id}">
                        </div>
                    </c:if>

                    <!-- 普通添加物流时的订单选择 -->
                    <c:if test="${empty order}">
                        <div class="form-group">
                            <label for="order_id"><i class="fas fa-receipt tea-icon"></i> 选择订单</label>
                            <select id="order_id" name="order_id" class="form-control" required>
                                <option value="">请选择已支付的订单</option>
                                <c:forEach items="${orderList}" var="orderItem">
                                    <option value="${orderItem.order_id}">${orderItem.order_no} - ${orderItem.customer_name} - ¥${orderItem.total_amount}</option>
                                </c:forEach>
                            </select>
                            <small style="color: var(--text-secondary); margin-top: 5px; display: block;">
                                <i class="fas fa-info-circle"></i> 只显示已支付但未发货的订单
                            </small>
                        </div>
                    </c:if>

                    <div class="form-row">
                        <div class="form-col">
                            <div class="form-group">
                                <label for="logistics_no"><i class="fas fa-barcode tea-icon"></i> 物流单号</label>
                                <input type="text" id="logistics_no" name="logistics_no" class="form-control"
                                       value="${logisticsNo}" placeholder="请输入物流单号" required maxlength="50">
                                <c:if test="${not empty logisticsNo}">
                                    <small style="color: var(--text-secondary); margin-top: 5px; display: block;">
                                        <i class="fas fa-info-circle"></i> 系统已自动生成物流单号，您可以修改
                                    </small>
                                </c:if>
                            </div>
                        </div>
                        <div class="form-col">
                            <div class="form-group">
                                <label for="status"><i class="fas fa-flag tea-icon"></i> 物流状态</label>
                                <select id="status" name="status" class="form-control">
                                    <option value="0" selected>运输中</option>
                                    <option value="1">已送达</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="logistics_company"><i class="fas fa-truck tea-icon"></i> 物流公司</label>
                        <select id="logistics_company" name="logistics_company" class="form-control" required>
                            <option value="">请选择物流公司</option>
                            <option value="顺丰速运">顺丰速运</option>
                            <option value="圆通速递">圆通速递</option>
                            <option value="中通快递">中通快递</option>
                            <option value="申通快递">申通快递</option>
                            <option value="韵达速递">韵达速递</option>
                            <option value="百世快递">百世快递</option>
                            <option value="德邦快递">德邦快递</option>
                            <option value="京东物流">京东物流</option>
                            <option value="邮政EMS">邮政EMS</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="shipping_time"><i class="fas fa-calendar tea-icon"></i> 发货时间</label>
                        <input type="datetime-local" id="shipping_time" name="shipping_time" class="form-control">
                        <small style="color: var(--text-secondary); margin-top: 5px; display: block;">
                            <i class="fas fa-info-circle"></i> 可选，不填写则默认为当前时间
                        </small>
                    </div>

                    <!-- 仓库和库存选择 -->
                    <c:if test="${not empty order}">
                        <div class="form-header">
                            <i class="fas fa-warehouse tea-icon"></i> 仓库和库存管理
                        </div>

                        <div class="form-group">
                            <label for="warehouse_id"><i class="fas fa-warehouse tea-icon"></i> 选择发货仓库</label>
                            <select id="warehouse_id" name="warehouse_id" class="form-control" required onchange="loadWarehouseInventory()">
                                <option value="">请选择发货仓库</option>
                                <c:forEach items="${warehouses}" var="warehouse">
                                    <option value="${warehouse.warehouse_id}">${warehouse.warehouse_name} - ${warehouse.location}</option>
                                </c:forEach>
                            </select>
                        </div>

                        <div id="inventory-section" style="display: none;">
                            <div class="form-group">
                                <label><i class="fas fa-boxes tea-icon"></i> 仓库库存</label>
                                <div id="inventory-list" style="background: #f8f9fa; padding: 15px; border-radius: 4px; border: 1px solid #e1e5e9;">
                                    <!-- 库存信息将通过AJAX加载 -->
                                </div>
                            </div>
                        </div>
                    </c:if>

                    <div class="btn-group">
                        <button type="button" class="el-button" onclick="history.back()">
                            <i class="fas fa-times"></i> 取消
                        </button>
                        <button type="submit" class="el-button el-button--primary">
                            <i class="fas fa-save"></i> 保存
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // 侧边栏收缩状态
    let isCollapsed = false;

    // 切换侧边栏状态
    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        isCollapsed = !isCollapsed;

        if(isCollapsed) {
            sidebar.classList.add('collapsed');
            localStorage.setItem('sidebarCollapsed', 'true');
        } else {
            sidebar.classList.remove('collapsed');
            localStorage.setItem('sidebarCollapsed', 'false');
        }
    }

    // 页面加载时检查状态
    window.onload = function() {
        const savedState = localStorage.getItem('sidebarCollapsed');
        if(savedState === 'true') {
            document.getElementById('sidebar').classList.add('collapsed');
            isCollapsed = true;
        }

        // 设置默认发货时间为当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const defaultTime = `${year}-${month}-${day}T${hours}:${minutes}`;
        document.getElementById('shipping_time').value = defaultTime;

        // 随机选择物流公司
        randomSelectLogisticsCompany();

        // 表单提交验证
        document.querySelector('form').addEventListener('submit', function(e) {
            const orderId = document.getElementById('order_id').value;
            const logisticsNo = document.getElementById('logistics_no').value.trim();
            const logisticsCompany = document.getElementById('logistics_company').value;

            if(!orderId) {
                alert('请选择订单');
                e.preventDefault();
                return;
            }

            if(!logisticsNo) {
                alert('物流单号不能为空');
                e.preventDefault();
                return;
            }

            if(!logisticsCompany) {
                alert('请选择物流公司');
                e.preventDefault();
                return;
            }
        });
    }

    // 随机选择物流公司
    function randomSelectLogisticsCompany() {
        const logisticsSelect = document.getElementById('logistics_company');
        const options = logisticsSelect.options;
        if (options.length > 1) {
            const randomIndex = Math.floor(Math.random() * (options.length - 1)) + 1;
            logisticsSelect.selectedIndex = randomIndex;
        }
    }

    // 加载仓库库存
    function loadWarehouseInventory() {
        const warehouseId = document.getElementById('warehouse_id').value;
        const inventorySection = document.getElementById('inventory-section');
        const inventoryList = document.getElementById('inventory-list');

        if (!warehouseId) {
            inventorySection.style.display = 'none';
            return;
        }

        // 显示加载中
        inventoryList.innerHTML = '<p><i class="fas fa-spinner fa-spin"></i> 正在加载库存信息...</p>';
        inventorySection.style.display = 'block';

        // AJAX请求获取库存信息
        fetch('LogisticsServlet?action=getInventory&warehouseId=' + warehouseId)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayInventory(data.inventory);
                } else {
                    inventoryList.innerHTML = '<p style="color: #f56c6c;"><i class="fas fa-exclamation-triangle"></i> ' + data.message + '</p>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                inventoryList.innerHTML = '<p style="color: #f56c6c;"><i class="fas fa-exclamation-triangle"></i> 加载库存信息失败</p>';
            });
    }

    // 显示库存信息
    function displayInventory(inventory) {
        const inventoryList = document.getElementById('inventory-list');
        let html = '<h4>当前仓库库存：</h4><table style="width: 100%; border-collapse: collapse;">';
        html += '<thead><tr style="background: #e1e5e9;"><th style="padding: 8px; border: 1px solid #ddd;">茶叶名称</th><th style="padding: 8px; border: 1px solid #ddd;">当前库存</th><th style="padding: 8px; border: 1px solid #ddd;">需要数量</th><th style="padding: 8px; border: 1px solid #ddd;">状态</th></tr></thead><tbody>';

        <c:if test="${not empty orderItems}">
            const orderItems = [
                <c:forEach items="${orderItems}" var="item" varStatus="status">
                    {teaId: ${item.tea_id}, teaName: '${item.tea_name}', quantity: ${item.quantity}}${!status.last ? ',' : ''}
                </c:forEach>
            ];

            orderItems.forEach(orderItem => {
                const inventoryItem = inventory.find(inv => inv.tea_id === orderItem.teaId);
                const currentStock = inventoryItem ? inventoryItem.quantity : 0;
                const sufficient = currentStock >= orderItem.quantity;
                const statusText = sufficient ? '<span style="color: #67c23a;">库存充足</span>' : '<span style="color: #f56c6c;">库存不足</span>';

                html += `<tr>
                    <td style="padding: 8px; border: 1px solid #ddd;">\${orderItem.teaName}</td>
                    <td style="padding: 8px; border: 1px solid #ddd;">\${currentStock}</td>
                    <td style="padding: 8px; border: 1px solid #ddd;">\${orderItem.quantity}</td>
                    <td style="padding: 8px; border: 1px solid #ddd;">\${statusText}</td>
                </tr>`;
            });
        </c:if>

        html += '</tbody></table>';
        inventoryList.innerHTML = html;
    }
</script>
</body>
</html>
